package com.ice.core.client.ha;

import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.SneakyThrows;
import org.springframework.cloud.client.ServiceInstance;

import java.util.List;

/**
 * Discovery making nacos to find server
 * @author guangming
 */
@Setter
@RequiredArgsConstructor
public class IceServerHaNacosDiscovery implements IceServerHaDiscovery {
    private static final String NACOS_PREFIX = "nacos";
    private final NacosServiceDiscovery nacosServiceDiscovery;
    private boolean support;
    private String port = "18121";
    private String serverName = "ice-server";

    @Override
    public boolean support() {
        return support;
    }

    @Override
    public void init(String server) {
        if (server.startsWith(NACOS_PREFIX)) {
            support = true;
            String[] serverAndPort = server.split(":");
            if (serverAndPort.length == 2) {
                port = serverAndPort[1];
            }
        } else {
            support = false;
        }
    }

    @Override
    public String refreshServerLeaderAddress() throws Exception {
        return getServerLeaderAddress();
    }

    @SneakyThrows
    @Override
    public String getServerLeaderAddress() {
        if (!support) {
            return null;
        }
        List<ServiceInstance> instances = nacosServiceDiscovery.getInstances(serverName);
        if (instances == null || instances.isEmpty()) {
            throw new RuntimeException("Can not get ice server from nacos server");
        }
        return instances.get(0).getHost() + ":" + port;
    }

    @Override
    public void destroy() {
    }
}
